package org.sjs.dreamfly.common.util

import android.util.Log
import java.util.*

object LogUtil {

    private const val fullLogEnabled = false

    fun d(tag: String, msg: String = "", ignore: Boolean = false) {
        if (ignore) return
        val output = buildMessage(msg)
        if (!fullLogEnabled || output.length < 4000) {
            Log.d(tag, output)
        } else {
            var count = 0;
            while (count <= output.length) {
                Log.d(tag, output.substring(count, if (count + 4000 < output.length) count + 4000 else output.length))
                count += 4000
            }
        }
    }

    fun d(msg: String = "", ignore: Boolean = false) {
        val tag: String = getTag()
        d(tag, msg, ignore)
    }

    fun e(msg: String = "") {
        val output = buildMessage(msg)
        if (!fullLogEnabled || output.length < 4000) {
            Log.e(getTag(), output)
        } else {
            var count = 0;
            while (count <= output.length) {
                Log.d(getTag(), output.substring(count, if (count + 4000 < output.length) count + 4000 else output.length))
                count += 4000
            }
        }
    }

    private fun getTag(): String {
        val trace = Throwable().fillInStackTrace().stackTrace
        var callingClass = ""
        for (i in 2 until trace.size) {
            if (trace[i].className != LogUtil::class.java.canonicalName) {
                callingClass = trace[i].className
                callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1)
                break
            }
        }
        return callingClass
    }

    private fun buildMessage(msg: String): String {
        val trace = Throwable().fillInStackTrace().stackTrace
        var caller: String? = ""
        for (i in 2 until trace.size) {
            if (trace[i].className != LogUtil::class.java.canonicalName) {
                caller = trace[i].methodName
                break
            }
        }
        return String.format(Locale.US, "[%d] %s: %s", Thread.currentThread().id, caller, msg)
    }
}